package com.java.gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.FileChooserUI;
import javax.swing.JTextField;
import javax.swing.JLabel;

import java.awt.Color;

import javax.swing.SwingConstants;

import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JProgressBar;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import org.apache.commons.io.FileUtils;

import com.java.fork.CopyFiles;

public class MainFrame extends JFrame {

	private JPanel contentPane;
	private JTextField txt_Input;
	private JTextField txt_Output;
	private JTextField txt_numberThread;
	private int countFileInput = 0;
	private JCheckBox chckbxReadProperties;
	String pathInput = "";
	String pathOutput = "";
	public static JTextArea textArea;
	private ForkJoinPool pool;
	private Thread queryThread = new Thread();
	public static boolean checkCancel = false;
	public static JProgressBar progressBar;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame frame = new MainFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainFrame() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 510, 428);
		setResizable(false);
		setLocationRelativeTo(null);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblNewLabel = new JLabel("Final Exercise Java Fundamental");
		lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 30));
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel.setForeground(Color.BLUE);
		lblNewLabel.setBounds(21, 11, 452, 29);
		contentPane.add(lblNewLabel);

		JLabel lblInput = new JLabel("Input:");
		lblInput.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblInput.setBounds(31, 53, 51, 23);
		contentPane.add(lblInput);

		txt_Input = new JTextField();
		txt_Input.setBounds(92, 54, 247, 23);
		contentPane.add(txt_Input);
		txt_Input.setColumns(10);

		JButton btnInput = new JButton("Input", new ImageIcon(
				"resources/io.png"));
		btnInput.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setMultiSelectionEnabled(true);
				fileChooser.setDialogTitle("Choose File Input");
				fileChooser.showOpenDialog(null);
				if (chckbxReadProperties.isSelected() == true) {
					if (!fileChooser.getSelectedFile().getAbsoluteFile()
							.getName().equals("config.properties")) {
						JOptionPane.showMessageDialog(null,
								"Please choose file name: config.properties");
					} else {
						txt_Input.setText(fileChooser.getSelectedFile()
								.getAbsolutePath());
					}
				} else if (fileChooser.getSelectedFiles() != null) {
					File[] f = fileChooser.getSelectedFiles();
					for (int i = 0; i < f.length; i++) {
						countFileInput++;
						pathInput += f[i].getAbsolutePath() + ";";
					}
					txt_Input.setText(pathInput);
				}
				txt_Output.setText("");
			}
		});
		btnInput.setFont(new Font("Times New Roman", Font.BOLD, 15));
		btnInput.setBounds(349, 51, 107, 29);
		contentPane.add(btnInput);

		JLabel lblOutput = new JLabel("Output:");
		lblOutput.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblOutput.setBounds(31, 90, 56, 23);
		contentPane.add(lblOutput);

		txt_Output = new JTextField();
		txt_Output.setColumns(10);
		txt_Output.setBounds(92, 88, 247, 23);
		contentPane.add(txt_Output);

		JButton btnOutput = new JButton("Output", new ImageIcon(
				"resources/io.png"));
		btnOutput.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setDialogTitle("Choose File/Folder Output");
				fileChooser
						.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
				fileChooser.showOpenDialog(null);
				if (fileChooser.getSelectedFile() != null) {
					if ((countFileInput > 1 || chckbxReadProperties
							.isSelected())
							&& fileChooser.getSelectedFile().isFile()) {
						JOptionPane
								.showMessageDialog(null,
										"Because you choose multi file/config.properties So output must folder");
					} else {
						pathOutput = fileChooser.getSelectedFile()
								.getAbsolutePath();
						txt_Output.setText(pathOutput);
					}
				}
			}
		});
		btnOutput.setFont(new Font("Times New Roman", Font.BOLD, 15));
		btnOutput.setBounds(349, 84, 107, 29);
		contentPane.add(btnOutput);

		JLabel lblNumberThread = new JLabel("Number Thread:");
		lblNumberThread.setForeground(Color.RED);
		lblNumberThread.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblNumberThread.setBounds(31, 124, 123, 23);
		contentPane.add(lblNumberThread);

		txt_numberThread = new JTextField();
		txt_numberThread.setColumns(10);
		txt_numberThread.setBounds(157, 125, 65, 23);
		contentPane.add(txt_numberThread);

		chckbxReadProperties = new JCheckBox("Read properties file");
		chckbxReadProperties.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				if (chckbxReadProperties.isSelected()) {
					txt_Input.setText("");
					txt_Output.setText("");
					JOptionPane.showMessageDialog(null,
							"Please choose file name: config.properties");
				}
			}
		});
		chckbxReadProperties.setFont(new Font("Times New Roman", Font.ITALIC,
				14));
		chckbxReadProperties.setBounds(228, 125, 155, 23);
		contentPane.add(chckbxReadProperties);

		textArea = new JTextArea();
		JScrollPane scrollPane = new JScrollPane(textArea);
		scrollPane.setBounds(31, 165, 425, 128);
		contentPane.add(scrollPane);

		JLabel lblProgress = new JLabel("Progress:");
		lblProgress.setFont(new Font("Times New Roman", Font.BOLD, 15));
		lblProgress.setBounds(31, 309, 73, 18);
		contentPane.add(lblProgress);

		progressBar = new JProgressBar();
		progressBar.setValue(0);
		progressBar.setStringPainted(true);
		progressBar.setForeground(Color.BLUE);
		progressBar.setBounds(133, 304, 323, 29);
		contentPane.add(progressBar);

		JPanel panel = new JPanel();
		panel.setBackground(Color.GRAY);
		panel.setBounds(0, 344, 504, 45);
		contentPane.add(panel);
		panel.setLayout(null);

		JButton btnCopy = new JButton("Copy", new ImageIcon(
				"resources/copy.png"));
		btnCopy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (txt_Input.getText().equals("")
						|| txt_Output.getText().equals("")) {
					JOptionPane.showMessageDialog(null,
							"Input and Output not null");
					return;
				}

				try {
					int a = Integer.parseInt(txt_numberThread.getText());
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(null,
							"Number thread must be a number");
					return;
				}

				if (chckbxReadProperties.isSelected()) {
					queryThread = new Thread() {
						public synchronized void run() {
							File f = new File(txt_Input.getText());
							try {
								FileInputStream is = new FileInputStream(f);
								InputStreamReader isr = new InputStreamReader(
										is);
								BufferedReader br = new BufferedReader(isr);
								String line;
								String[] pathFiles = null;
								List<String> list = new ArrayList<String>();
								while ((line = br.readLine()) != null) {
									pathFiles = line.split("=");
									list.add(pathFiles[1]);
								}

								textArea.setText("");
								String[] arrayPathFile = list
										.toArray(new String[list.size()]);
								
								for (int i = 0; i < arrayPathFile.length; i++) {
									File fileSource = new File(arrayPathFile[i]);
									if(!fileSource.exists()){
										JOptionPane.showMessageDialog(null,
												"File copy in config.properties not exist");
										return;
									}
								}
								
								File fOuput = new File(txt_Output.getText());
								if (fOuput.isDirectory() == false && fOuput.exists() == false) {
									JOptionPane.showMessageDialog(null,
											"Directory destination not exist");
									return;
								}
								
								CopyFiles cf = new CopyFiles(arrayPathFile, 0,
										arrayPathFile.length, txt_Output.getText());
								pool = new ForkJoinPool(Integer
										.parseInt(txt_numberThread.getText()));
								pool.invoke(cf);
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								JOptionPane.showMessageDialog(null,
										"File config.properties not found");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					};
					queryThread.start();

				} else {
					queryThread = new Thread() {
						public synchronized void run() {
							textArea.setText("");
							String[] pathFiles = txt_Input.getText().split(";");
							for (int i = 0; i < pathFiles.length; i++) {
								File fileSource = new File(pathFiles[i]);
								if(!fileSource.exists()){
									JOptionPane.showMessageDialog(null,
											"File source not exist");
									return;
								}
							}
							File fOuput = new File(txt_Output.getText());
							if (fOuput.isDirectory() == false && fOuput.exists() == false) {
								JOptionPane.showMessageDialog(null,
										"Directory destination not exist");
								return;
							}
							
							CopyFiles cf = new CopyFiles(pathFiles, 0,
									pathFiles.length, txt_Output.getText());
							pool = new ForkJoinPool(Integer
									.parseInt(txt_numberThread.getText()));
							pool.invoke(cf);
						}
					};
					queryThread.start();
				}
				if (checkCancel) {
					checkCancel = false;
				}
			}
		});
		btnCopy.setBounds(100, 5, 95, 34);
		panel.add(btnCopy);

		JButton btnCancel = new JButton("Cancel", new ImageIcon(
				"resources/pause.png"));
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int select = JOptionPane.showConfirmDialog(null, "Are you sure ? ", "Cancel Copy", JOptionPane.YES_NO_OPTION);
				if (select == JOptionPane.YES_OPTION) {
					if (queryThread.isAlive()) {
						queryThread.interrupt();
						checkCancel = true;
					}
				}
			}
		});
		btnCancel.setBounds(205, 5, 107, 34);
		panel.add(btnCancel);

		JButton btnExit = new JButton("Exit", new ImageIcon(
				"resources/exit.png"));
		btnExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		btnExit.setBounds(322, 5, 95, 34);
		panel.add(btnExit);

	}
}
